package com.ls.herostory.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 11:21
 * @since
 */
public class AsyncOperationProcessor {
    private final static Logger logger = LoggerFactory.getLogger(AsyncOperationProcessor.class);

    private static AsyncOperationProcessor asyncOperationProcessor = new AsyncOperationProcessor();

    /**
     * 只有一个线程的线程池
     */
    private ThreadPoolExecutor executor;

    private AsyncOperationProcessor(){
        executor = new ThreadPoolExecutor(4, 4,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new MyThreadFactory("thread_async"));
    }

    public static AsyncOperationProcessor getIntance(){
        return asyncOperationProcessor;
    }

    public void process(AsyncOperation asyncOperation){
        executor.submit(() ->{
            asyncOperation.doAsync();

            // 回到主线程执行
            MainMsgProcessor.getIntance().process(asyncOperation::doFinish);
        });
    }

    public void process(Runnable runnable){
        executor.submit(runnable);
    }
}
